import { Module } from 'vuex';
import { loginState } from './types';
import { rootState } from '../types';
import { login, getMenu } from '@/api/login';
import router from '@/router/index';
import cache from '@/utils/cache';
import { mapMenusToRoutes } from '@/utils/map-route';

const loginModule: Module<loginState, rootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      menu: [],
      roleMenu: []
    };
  },
  getters: {},
  mutations: {
    SET_TOKEN(state, token: string) {
      state.token = token;
    },
    SET_ROLEMENU(state, roleMenu: any) {
      state.roleMenu = roleMenu;
    },
    SET_MENU(state, menu: any) {
      state.menu = menu;
      // 组装路由放到route里面
      const routes = mapMenusToRoutes(menu);
      routes.forEach((e) => {
        router.addRoute('main', e);
      });
    },
    SET_USERINFO(state, userInfo: any) {
      state.userInfo = userInfo;
    }
  },
  actions: {
    async loginAction({ commit }, paylod: any) {
      // 获取登录信息
      console.log(paylod);
      const data: any = await login();
      commit('SET_TOKEN', data.data.token);
      cache.setCache('token', data.data.token);
      // 模拟添加用户信息，当前只有用户名和用户密码
      commit('SET_USERINFO', paylod);
      cache.setCache('userInfo', paylod);
      // 获取菜单数据
      const menu: any = await getMenu();
      commit('SET_MENU', menu);
      cache.setCache('menu', menu);
      // console.log(menu);
      router.push('/main');
    },
    setupLoginStore({ commit }) {
      const token = cache.getCache('token');
      const menu = cache.getCache('menu');
      const userInfo = cache.getCache('userInfo');
      if (token) {
        commit('SET_TOKEN', token);
      }
      if (menu) {
        commit('SET_MENU', menu);
      }
      if (userInfo) {
        commit('SET_USERINFO', userInfo);
      }
    }
  }
};

export default loginModule;
